package edu.ubb.scp.gui;

import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Random;

import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;

import edu.ubb.scp.dao.BaseDAO;
import edu.ubb.scp.dao.DAOFactory;
import edu.ubb.scp.exception.UnsafeException;
import edu.ubb.scp.model.Model;
import edu.ubb.scp.model.Test;

public class TestGui extends JDialog {
	
	public CustomerGui gui;
	public JPanel contentPane = new JPanel(new BorderLayout());
	private JPanel buttonPane = new JPanel(new FlowLayout());
	private JTextField field = new JTextField(10); 
	public TestGui(CustomerGui cgui) {
		super(cgui, true);
		gui = cgui;
		setSize(350,250);
		init();
		setVisible(true);		
	}
	
	private void init() {
		DAOFactory df = DAOFactory.getInstance();
		BaseDAO bd = df.getBaseDAO();
		ArrayList<Model> list = bd.select(Test.class);
		Random rand = new Random();
		final Test t = (Test) list.get(Math.abs(rand.nextInt()) % (list.size()));
		
		contentPane.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
		JScrollPane testHolder = new JScrollPane();
		testHolder.setBorder(BorderFactory.createEtchedBorder());
		testHolder.setViewportView(new JLabel(t.getData()));
		contentPane.add(testHolder, BorderLayout.CENTER);
		JButton button = new JButton("Answer!");
		buttonPane.add(field);
		buttonPane.add(button);
		
		button.addActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent arg0) {
				if (field.getText().equals(t.getAnswer())) {
					try {
						gui.confirmOrder();
						dispose();
					} catch (UnsafeException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
				
			}
		});
		
		contentPane.add(buttonPane, BorderLayout.NORTH);
		setContentPane(contentPane);
		
	}
}
